package com.supor.aiot.food.utils;

import android.content.Context;
import android.media.AudioManager;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.MimeTypeMap;
import android.widget.Adapter;
import android.widget.FrameLayout;

import androidx.annotation.DimenRes;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.Util;
import com.android.baseconfig.config.Config;
import com.pili.pldroid.player.AVOptions;
import com.pili.pldroid.player.PLOnInfoListener;
import com.pili.pldroid.player.widget.PLVideoTextureView;
import com.supor.aiot.food.R;
import com.supor.aiot.food.adapter.RecomondRecipeAdapter;
import com.supor.aiot.food.bean.RecipeHotBean;
import com.supor.md_video.tools.TextureVideoViewOutlineProvider;

public class VideoScrollPlayerManager {
    public final static String TAG = "VideoScrollPlayerManager_Info";
    private int currentViewPosition;
    private int oldPosition;
    private LinearLayoutManager layoutManager;
    private RecyclerView recyclerView;
    private RecomondRecipeAdapter recipeAdapter;
    private Context mContext;
    private PLVideoTextureView plVideoTextureView;
    private FrameLayout playerContainer;
    private AudioManager audioManager;
    private AudioManager.OnAudioFocusChangeListener afChangeListener;


    public void init(Context mContext, LinearLayoutManager layoutManager, RecomondRecipeAdapter recipeAdapter, RecyclerView recyclerView) {
        this.layoutManager = layoutManager;
        this.recipeAdapter = recipeAdapter;
        this.recyclerView = recyclerView;
        this.mContext = mContext;
        getPlayerContainer();
        bindRecyclerView();
    }

    public void bindRecyclerView() {
//        recipeAdapter.bindVideoPlayer(this);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    if (layoutManager.findFirstCompletelyVisibleItemPosition() < 0) {
                        stopListPlay();
                        return;
                    }
                    currentViewPosition = layoutManager.findFirstCompletelyVisibleItemPosition();
                    if (currentViewPosition == oldPosition && plVideoTextureView.isPlaying()
                            || recipeAdapter.getData().get(currentViewPosition).getItemType() == RecipeHotBean.TYPE_LOAD) {
                        return;
                    }
                    stopListPlay();
                    if (currentViewPosition < 0) {
                        return;
                    }
                    startListPlay();
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
//                startListPlay();
            }
        });
    }

    public void bindLayoutManager(LinearLayoutManager layoutManager) {

    }

    private PLVideoTextureView getTextureView() {
        if (null == plVideoTextureView) {
            plVideoTextureView = new PLVideoTextureView(mContext);

            plVideoTextureView.setLayoutParams(new ViewGroup.LayoutParams(mContext.getResources().getDimensionPixelOffset(R.dimen.dp_233),
                    mContext.getResources().getDimensionPixelOffset(R.dimen.dp_415)));
            plVideoTextureView.setDisplayAspectRatio(PLVideoTextureView.ASPECT_RATIO_PAVED_PARENT);
            plVideoTextureView.setLooping(true);
            AVOptions options = new AVOptions();
            options.setInteger(AVOptions.KEY_FAST_OPEN, 1);
            options.setString(AVOptions.KEY_CACHE_DIR, mContext.getCacheDir().getAbsolutePath());
            plVideoTextureView.setAVOptions(options);
            plVideoTextureView.setOutlineProvider(new TextureVideoViewOutlineProvider(30));
            plVideoTextureView.setClipToOutline(true);
        }
        return plVideoTextureView;
    }

    private FrameLayout getPlayerContainer() {
        if (null == playerContainer) {
            playerContainer = new FrameLayout(mContext);
//            android:layout_width="@dimen/dp_233"
//            android:layout_height="@dimen/dp_415"
            playerContainer.setLayoutParams(new ViewGroup.LayoutParams(mContext.getResources().getDimensionPixelOffset(R.dimen.dp_233),
                    mContext.getResources().getDimensionPixelOffset(R.dimen.dp_415)));
            playerContainer.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (getTextureView().isPlaying()) {
//                        onPause();
                    } else {
//                        onResume();
                    }
                }
            });
            playerContainer.addView(getTextureView());

        }
        return playerContainer;
    }

    public void stopListPlay() {
//        currentViewPosition = position;
//        if (currentViewPosition == oldPosition && listViewLife != 0) {
//            return;
//        }

        ViewGroup oldContainer = (ViewGroup) getPlayerContainer().getParent();
        if (null != oldContainer) {
            oldContainer.removeAllViews();
        }

        if (getTextureView().isPlaying()) {
            getTextureView().pause();
        }
        View oldCoverView = recipeAdapter.getViewByPosition(oldPosition, R.id.iv_recomond_recipe);
        if (null != oldCoverView && oldCoverView.getVisibility() != View.VISIBLE) {
            oldCoverView.setVisibility(View.VISIBLE);
        }
        View newCoverView = recipeAdapter.getViewByPosition(currentViewPosition, R.id.iv_recomond_recipe);
        if (null != newCoverView && newCoverView.getVisibility() != View.VISIBLE) {
            newCoverView.setVisibility(View.VISIBLE);
        }
    }

    public void startListPlay() {
        if (currentViewPosition == oldPosition && plVideoTextureView.isPlaying()) {
            return;
        }
        getAudioFocus();
        oldPosition = currentViewPosition;

        FrameLayout container = (FrameLayout) recipeAdapter.getViewByPosition(oldPosition, R.id.fl_container);
        if (null == container) {
            return;
        }
        container.addView(getPlayerContainer());
        RecipeHotBean recipeHotBean = recipeAdapter.getData().get(oldPosition);
        getTextureView().setVideoPath(recipeAdapter.getData().get(oldPosition).getHighVertical());
        getTextureView().setOnInfoListener(new PLOnInfoListener() {
            @Override
            public void onInfo(int what, int i1) {
//                Logc.d(TAG, "what:" + what + "  info:" + i1);
                if (what == PLOnInfoListener.MEDIA_INFO_VIDEO_RENDERING_START) {
                    View viewCover = recipeAdapter.getViewByPosition(oldPosition, R.id.iv_recomond_recipe);
                    if (null != viewCover) {
                        viewCover.setVisibility(View.INVISIBLE);
                    }
                }
            }
        });
        getTextureView().setVolume(recipeHotBean.getLocalIsMuteEnb(), recipeHotBean.getLocalIsMuteEnb());

        getTextureView().start();
    }

    private void getAudioFocus() {
        if (null == audioManager) {
            audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
        }
        if (null == audioManager) {
            afChangeListener = new AudioManager.OnAudioFocusChangeListener() {
                public void onAudioFocusChange(int focusChange) {
                    if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
                        stopListPlay();
                    } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
                    } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
                    } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
                    }
                }
            };
        }

        // Request audio focus for playback
        int result = audioManager.requestAudioFocus(afChangeListener,
                // Use the music stream.
                AudioManager.STREAM_MUSIC,
                // Request permanent focus.
                AudioManager.AUDIOFOCUS_GAIN);
        Logc.d(TAG, "result = " + result);

//        if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
//
//        }
    }

    public void setVolume(float volume) {
        getTextureView().setVolume(volume, volume);
    }

    public void onPause() {
        if (null != plVideoTextureView) {
            plVideoTextureView.pause();
        }
//        if (null != mIvPlay) {
//            mIvPlay.setVisibility(View.VISIBLE);
//        }
    }

    public void onResume() {
        if (null != plVideoTextureView) {
            plVideoTextureView.start();
        }
//        if (null != mIvPlay) {
//            mIvPlay.setVisibility(View.INVISIBLE);
//        }
    }

    public void destoryManager() {
        if (null != plVideoTextureView) {
            plVideoTextureView.stopPlayback();
        }
    }

    public int getCurrentViewPosition() {
        return currentViewPosition;
    }

    public int getOldPosition() {
        return oldPosition;
    }

    public boolean isPlaying() {
        return getTextureView().isPlaying();
    }
}